package com.sliansoft.wechat.appcenter.kit;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.sliansoft.wechat.appcenter.context.WeixinContext;
import com.sliansoft.wechat.appcenter.context.WeixinFinalValue;
import com.sliansoft.wechat.appcenter.model.SuiteWithBLOBs;

import net.sf.json.JSONObject;

public class WeixinKit {
	
	/**
	 * 获取获取企业号access_token
	 * 
	 * @param permanent_code
	 * @param suite
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String getAccessToken(String permanent_code,String corp_id,SuiteWithBLOBs suite) {
		String url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token=SUITE_ACCESS_TOKEN";
		String suite_access_token = WeixinKit.getSuiteAccessToken(suite);
		url = url.replace("SUITE_ACCESS_TOKEN", suite_access_token);
		Map<String, String> map = new HashMap<String, String>();
		map.put("suite_id", suite.getSuiteId());
		map.put("auth_corpid", corp_id);// 需要在获取永久授权码的同时获取
		map.put("permanent_code", permanent_code);
		String json = JSONObject.fromObject(map).toString();
		String jsonresult = WeixinKit.postReq(url, json, "application/json");
		System.out.println(jsonresult);
		JSONObject jsonObject = JSONObject.fromObject(jsonresult);
		
		Map<String, String> mapresult = JSONObject.fromObject(jsonObject);
		String access_token = mapresult.get("access_token");
		System.out.println("access_token:"+access_token);
		return access_token;
	}
	
	
	/**
	 * 获取SuiteAccessToken并保存
	 * 
	 * @param suite
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String getSuiteAccessToken(SuiteWithBLOBs suite) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("suite_id", suite.getSuiteId());
		map.put("suite_secret", suite.getSuiteSecret());
		map.put("suite_ticket", WeixinContext.getSuiteTicket(suite.getSuiteId()));
		String json = JSONObject.fromObject(map).toString();
		String jsonresult = WeixinKit.postReq(WeixinFinalValue.GET_SUITE_ACCESS_TOKEN, json, "application/json");
		//System.out.println( WeixinContext.getSuiteTicket(suite.getSuiteId()));
		//System.out.println(jsonresult);

		JSONObject jsonObject = JSONObject.fromObject(jsonresult);
		Map<String, String> mapresult = JSONObject.fromObject(jsonObject);
		String suite_access_token = mapresult.get("suite_access_token");
		//System.out.println("suite_id:"+ suite.getSuiteId()+"----------suite_ticket"+WeixinContext.getSuiteTicket(suite.getSuiteId())+"-----------suite_access_token:"+suite_access_token);
		//WeixinContext.setSuiteAccessToken(suite_access_token);
		return suite_access_token;
	}
	
	/**
	 * 获取PreAuthCode并保存
	 * 
	 * @param suite_access_token
	 * @param suite
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String getPreAuthCode(String suite_access_token, SuiteWithBLOBs suite) {
		String url = WeixinFinalValue.GET_PRE_AUTH_CODE.replace("SUITE_ACCESS_TOKEN", suite_access_token);
		Map<String, String> map = new HashMap<String, String>();
		map.put("suite_id", suite.getSuiteId());
		/* map.put("appid", ""); */
		String json = JSONObject.fromObject(map).toString();
		String jsonresult = WeixinKit.postReq(url, json, "application/json");
		//System.out.println("jsonresult:"+jsonresult);
		
		JSONObject jsonObject = JSONObject.fromObject(jsonresult);
		Map<String, String> mapresult = JSONObject.fromObject(jsonObject);
		String pre_auth_code = mapresult.get("pre_auth_code");
		//System.out.println("pre_auth_code:"+pre_auth_code);
		//WeixinContext.setPreAuthCode(pre_auth_code);
		return pre_auth_code;
	}
	
	/**
	 * post请求
	 * 
	 * @param url
	 * @param data
	 * @param type
	 * @return
	 */
	public static String postReq(String url, String data, String type) {
		CloseableHttpClient client = null;
		CloseableHttpResponse resp = null;
		try {
			client = HttpClients.createDefault();
			HttpPost post = new HttpPost(url);
			post.addHeader("Content-Type", type);
			StringEntity entity = new StringEntity(data, ContentType.create(type, "utf-8"));
			post.setEntity(entity);
			resp = client.execute(post);
			int sc = resp.getStatusLine().getStatusCode();
			if (sc >= 200 && sc < 300) {
				String str = EntityUtils.toString(resp.getEntity());
				return str;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (client != null)
					client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (resp != null)
					resp.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * get请求
	 * @param url
	 * @return
	 */
	public static String sendGet(String url) {
		String content = null;
		CloseableHttpClient client = null;
		CloseableHttpResponse resp = null;
		try {
			client = HttpClients.createDefault();
			HttpGet get = new HttpGet(url);
			get.addHeader("Content-type","application/json;charset=utf-8");
			resp = client.execute(get);
			int statusCode = resp.getStatusLine().getStatusCode();
			if (statusCode >= 200 && statusCode < 400) {
				HttpEntity entity = resp.getEntity();
				if (entity != null)
					content = EntityUtils.toString(entity,"utf-8");
			}
			return content.toString();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (resp != null)
					resp.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (client != null)
					client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
